package com.zx._08_网络.cpt3_udp;

import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.InetAddress;
import java.util.Scanner;


public class Client {

    // 定义发送目的地
    public static final int PORT = 30000;
    public static final String DECT_IP = "127.0.0.1";
    // 定义每个数据报的大小为4KB
    private static final int DATA_LEN = 4096;
    // 指定接受数据报的字节数组
    byte[] inBuff = new byte[DATA_LEN];
    String[] books = {"aaa", "bbb", "ccc", "ddd"};
    // 定义一个用于接收数据报的DatagramPacket对象， 设置它的数据报的字节数组和大小
    private DatagramPacket inPacket = new DatagramPacket(inBuff, inBuff.length);
    // 定义一个用于发送数据报的DatagramPacket
    private DatagramPacket outPacket;

    public static void main(String[] args) throws IOException {
        System.out.println("Client");
        new Client().init();
    }

    public void init() throws IOException {
        // 创建一个DatagramSocket对象
        DatagramSocket socket = new DatagramSocket();
        this.outPacket = new DatagramPacket(new byte[0], 0, InetAddress.getByName(DECT_IP), PORT);
        Scanner scan = new Scanner(System.in);
        while (scan.hasNextLine()) {
            byte[] buff = scan.nextLine().getBytes();
            this.outPacket.setData(buff);
            socket.send(outPacket);
            socket.receive(inPacket);
            System.out.println(new String(this.inBuff, 0, this.inPacket.getLength()));
        }
    }
}
